<template>
    <div style="background: #F4F7FD;padding-bottom:15px;">
        <navTop></navTop>
        <titleTab :examtitle="examtitle" :classlistbox="classlistbox" @classIdDate="classIdDate" :className="className"></titleTab>
        <div class="contentzw" :style="screenWidth > 1400 ? 'width:1400px;;' : 'width:1200px;min-width:1200px;'">
            <div ref="leftPanel" class="contentzwLeft">
                <div :class="{ fixed: isFixed }">
                    <div class="searchtopbox">
                        <el-select v-model="selectvale" placeholder="全部" @change="selectvaluechange" clearable>
                            <el-option
                            v-for="item in searchAll"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                        <el-input v-model="studentName" placeholder="输入学生姓名" @change="studentnamechange" clearable></el-input>
                        <span>点击图标可收藏学生</span>
                    </div>
                    <ul>
                        <li v-for="(item,index) in attentionlist" :key="item.studentId" @click.stop="studentDetial(item,index)" :class="studentIndex==index?'hover':''" :title="item.studentName">
                            <i :class="item.starStatus==0?'iconfont active':'iconfont'" @click.stop="collect(item,index)">{{item.starStatus==0?'&#xe7a3;':'&#xe7a2;'}}</i>
                            {{item.studentName}}
                        </li>
                    </ul>
                </div>
            </div>
            <div class="contentzwRight">
                <div class="answerBox">
                    <div class="subobjquestion">
                        <div class="subobjquestionTitle">
                            学生作答概况
                        </div>
                    </div>
                    <el-table :data="studentAnswergk" border stripe
                        :header-cell-style="{ background: '#e8f0fa', color: '#2A303B', fontWeight: '500' }" class="custom-table"
                        tooltip-effect="dark" style="width: 100%">
                        <el-table-column prop="studentName" label="姓名" align="center" />
                        <el-table-column prop="examName" label="作业名称" align="center" width="340" />
                        <el-table-column prop="classSort" label="班名次" align="center" width="80" />
                        <el-table-column prop="scoreMark" label="得分/满分" align="center" />
                        <el-table-column prop="avgScore" label="均分差" align="center"  width="80" />
                        <el-table-column label="得分差" align="center" width="80">
                            <template slot-scope="scope">
                                {{scope.row.scoreRatio.toFixed(2)}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="subTime" label="提交时间" align="center" />
                        <el-table-column label="操作" width="90" align="center">
                            <template slot-scope="scope">
                                <span class="lookquestioncard" @click="showViewer">查看题卡</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="studentAvgDate">
                    <div class="studentAvgDateLeft">
                        <div class="subobjquestion">
                            <div class="subobjquestionTitle">
                                学生得分所在区间
                            </div>
                        </div>
                        <div class="studentAvgDateLeftContent">
                            <div ref="chartRef"  style="width:100%;height:224px;"></div>
                        </div>
                    </div>
                    <div class="studentAvgDateRight">
                        <div class="subobjquestion">
                            <div class="subobjquestionTitle">
                                均分离差对比
                            </div>
                        </div>
                        <div class="studentAvgDateLeftContent">
                            <div ref="chartRef1"  style="width:100%;height:224px;"></div>
                        </div>
                    </div>
                </div>
                <div class="answerBox">
                    <div class="subobjquestion">
                        <div class="subobjquestionTitle">
                            小题分详情
                        </div>
                    </div>
                     <el-table :data="smallquestiondetaillist"  border stripe
                        :header-cell-style="{ background: '#e8f0fa', color: '#2A303B', fontWeight: '500' }" class="custom-table"
                        tooltip-effect="dark" style="width: 100%">
                        <el-table-column 
                            v-for="(value, key) in smallquestiondetaillist[0]" 
                            :key="key"
                            :prop="key"
                            :label="key"
                            min-width="130"
                        ></el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <viewer
            class="viewer"
            ref="viewer"
            :images="paperImages"
            :shown="viewerVisible"
            @inited="viewerInited"
            >
            <template #default="{ images }">
            <img
                v-for="(image, index) in images"
                :key="index"
                :src="image.imagePath"
                style="display: none;"
            >
            </template>
            </viewer>
    </div>
</template>

<script>
import navTop from "../../components/homework/headtop.vue"
import titleTab from "../../components/analysis/titleTab.vue"
import * as echarts from 'echarts'
import {getanalysis,get,postanalysis} from '../../request/api.js'
import { mapGetters } from 'vuex';
import {encrypt,decrypt} from '../../utils/cryptojs'
export default{
    data(){
        return {
            examtitle:'',
            className:'',
            classlistbox:[],
            examId:'',
            classId:'',
            searchAll:[
                {
                    label:'全部',
                    value:1
                },
                {
                    label:'仅关注',
                    value:0
                }
            ],
            attentionlist:[
                {
                    name:'小王',
                    id:5,
                    collectIshow:false
                },
                {
                    name:'小王1',
                    id:5,
                    collectIshow:false
                },
                {
                    name:'小王2',
                    id:5,
                    collectIshow:false
                },
                {
                    name:'小王3',
                    id:5,
                    collectIshow:false
                },
                {
                    name:'小王4',
                    id:5,
                    collectIshow:false
                },
                {
                    name:'小王5',
                    id:5,
                    collectIshow:false
                },
                {
                    name:'小王6',
                    id:5,
                    collectIshow:false
                },
                {
                    name:'小王7',
                    id:5,
                    collectIshow:false
                },
                {
                    name:'小王8',
                    id:5,
                    collectIshow:false
                },
                {
                    name:'小王9',
                    id:5,
                    collectIshow:false
                }
            ],
            studentAnswergk:[],
            smallquestiondetaillist:[],
            chart:null,
            chart1:null,
            selectvale:'',
            studentName:'',
            studentIndex:0,
            userInfo:{},
            viewerVisible: false, // 控制查看器的显示状态
            paperImages:[],
            echartstudentscore:[],
            echartstudentscoreavg:[],
            images:[],
            isFixed: false,          // 是否固定
            offsetTop: 0 ,
            attention:'',
            studentNamedetail:'',
            studentScore:''
        }
    },
    mounted(){
        // 解密数据数据
        const teacherInfo = decrypt(localStorage.getItem('accessToken'))
        this.teacherInfo = JSON.parse(teacherInfo)
        this.examtitle = this.$route.query.title
        this.examId = this.$route.query.examId
        this.className = this.$route.query.classname
        this.getstudentlist()
        this.getOffsetTop();          // 初始计算
        window.addEventListener('scroll', this.handleScroll, { passive: true });
        window.addEventListener('resize', this.getOffsetTop);
    },
    methods:{
        //筛选关注
        selectvaluechange(val){
            if(val==0){
                this.attention=val
            }else{
                this.attention=''
            }
            console.info(this.attention,'this.attention')
            this.getstudentlist()
        },
        //搜索学生姓名
        studentnamechange(val){
            this.studentName = val
            this.getstudentlist()
        },
        //获取学生列表 
        async getstudentlist(){
            let option={
                classId:this.$route.query.classId,
                examId:this.$route.query.examId,
                teacherId:this.teacherInfo.teacherId,
                starStatus:this.attention===''?undefined:this.attention,
                studentName:this.studentName?this.studentName:undefined
            }
            await postanalysis(`api/student/getStudentInfoList`,option).then(res=>{
                if(res.code==200){
                    this.attentionlist = res.data
                    this.studentDetail(res.data[0].studentId)
                    this.smallquestiondetail(res.data[0].id)
                    this.getstudentQjscore(res.data[0].studentId)
                    this.getstudentAvg(res.data[0].studentId)
                    this.studentNamedetail=res.data[0].studentName
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        showViewer() {
            // 显示查看器并跳转到指定图片
            this.$viewer.view(0);
        },
        viewerInited(viewer) {
            // 在 viewer 初始化后，可以通过 this.$viewer 访问 viewer 实例
            this.$viewer = viewer;
        },
        // 切换学生查看详情
        studentDetial(con,index){
            this.studentId = con.studentId
            this.studentIndex = index
            this.studentNamedetail = con.studentName
            this.studentDetail(con.studentId)
            this.smallquestiondetail(con.id)
            this.getstudentQjscore(con.studentId)
            this.getstudentAvg(con.studentId)
            // alert('111')
        },
        //收藏取消收藏
        collect(con,index){
            // alert('22')
            this.attentionlist[index].starStatus = this.attentionlist[index].starStatus === 0 ? 1 : 0;
            let option={
                teacherId:this.teacherInfo.teacherId,
                studentId:con.studentId
            }
            if(con.starStatus==0){
                //收藏
                // alert('收藏')
                getanalysis('api/t_star_s/star',option).then(res=>{
                    if(res.code==200){
                        this.$message.success('收藏成功');
                    } else {
                        this.$message.error(res.message);
                    }
                })
            }else{
                //取消收藏
                // alert('取消收藏')
                getanalysis('api/t_star_s/unStar',option).then(res=>{
                    if(res.code==200){
                        this.$message.success('取消收藏');
                    } else {
                        this.$message.error(res.message);
                    }
                })
            }
        },
        //学生作答概况 
        async studentDetail(studentid){
            let option={
                studentId:studentid,
                classId:this.$route.query.classId,
                examId:this.$route.query.examId
            }
            await getanalysis('api/student/getStudentInfo',option).then(res=>{
                if(res.code==200){
                    const raw = res.data || []
                    this.studentAnswergk = Array.isArray(raw) ? raw : [raw]
                    this.studentScore = res.data.scoreMark.split('/')[0]
                    this.aveScore= res.data.avgScore
                    console.info('dsdfasdfsd',this.studentScore)
                    this.paperImages = JSON.parse(res.data.paperImages)
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        //小题分详情
        async smallquestiondetail(studentid){
            let option={
                studentSubmitId:studentid,
                examId:this.$route.query.examId
            }
            await postanalysis('api/questions/getStudentQuestions',option).then(res=>{
                if(res.code==200){
                    // this.studentNamedetail   this.smallquestiondetail
                    // this.studentAnswergk = res.data
                    let obj={'姓名':this.studentNamedetail,...res.data}
                    this.smallquestiondetaillist = [obj]
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        //获取学生得分所在区间 
        async getstudentQjscore(studentid){
            let option={
                classId:this.$route.query.classId,
                examId:this.$route.query.examId,
                studentId:studentid
            }
            await postanalysis('api/questions/getStudentScoreLevel',option).then(res=>{
                if(res.code==200){
                    this.echartstudentscore = res.data
                    // console.info(res.data.levelMap,'levelMap')
                    // 区间数组
                    const labels = Object.keys(res.data.levelMap);
                    // 数值数组
                    const values = Object.values(res.data.levelMap);
                    setTimeout(()=>{
                        this.initChart(labels,values)
                    },500)
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        //获取学生 均分利差对比
        async getstudentAvg(studentid){
            let option={
                classId:this.$route.query.classId,
                examId:this.$route.query.examId,
                studentId:studentid
            }
            await postanalysis('api/questions/getStudentScoreAvgLevel',option).then(res=>{
                if(res.code==200){
                    // this.echartstudentscoreavg = res.data
                    const labels = Object.keys(res.data.levelMap);
                    // 数值数组
                    const values = Object.values(res.data.levelMap);
                    setTimeout(()=>{
                        this.initChart1(labels,values)
                    },500)
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        // 获取班级
        async getclass(id) {
            let obj = {
                examId: id
            }
            await get('/work/class', obj)
                .then(res => {
                if (res.code == 200) {
                    this.classlistbox = res.data
                    this.classId = res.data[0].classId
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        initChart(label,value) {
            const studentIndex = label.findIndex(item => {
                const [min, max] = item.split('~').map(Number);
                return this.studentScore >= min && this.studentScore <= max;
            });
            this.chart = echarts.init(this.$refs.chartRef)
            const option = {
                color: ['#29CE67', '#A777FF', '#4985FF', '#FFAB77', '#FF7777'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'shadow' }
                },
                legend: {show: false},
                xAxis: {
                    type: 'category',
                    data: label,
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                series: [
                    {
                        data: value.map((v, idx) => ({
                            value: v,
                            itemStyle: {
                                color: (idx === studentIndex) ? '#29CE67' : '#4985FF'
                            }
                        })),
                        type: 'bar',
                    }
                ]
            }
            this.chart.setOption(option)
        },
        initChart1(label,value) {
            const studentIndex = label.findIndex(item => {
                const [min, max] = item.split('~').map(Number);
                return this.aveScore >= min && this.aveScore <= max;
            });
            this.chart1 = echarts.init(this.$refs.chartRef1)
            const labelTop = {
                show: true,
                position: 'top'
            };
            const option = {
                color: ['#29CE67', '#A777FF', '#4985FF', '#FFAB77', '#FF7777'],
                xAxis: {
                    max: 'dataMax',
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                yAxis: {
                    type: 'category',
                    data: label,
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                dataGroupId: '',
                animationDurationUpdate: 500,
                series: {
                    type: 'bar',
                    id: 'sales',
                    data: value.map((v, idx) => ({
                        value: v,
                        itemStyle: {
                            color: (idx === studentIndex) ? '#29CE67' : '#4985FF'
                        }
                    }))
                }
            };
            this.chart1.setOption(option)
        },
        classIdDate(val){

        },
        // 计算元素距离页面顶部的绝对高度
        getOffsetTop() {
            this.$nextTick(() => {
                const el = this.$refs.leftPanel;
                if (!el) return;
                let top = 0;
                let cur = el;
                while (cur) {
                top += cur.offsetTop;
                cur = cur.offsetParent;
                }
                this.offsetTop = top;
            });
        },
        // 滚动监听
        handleScroll() {
            const scrollY = window.pageYOffset || document.documentElement.scrollTop;
            this.isFixed = scrollY >= this.offsetTop;
        }
    },
    components: { navTop,titleTab },
    computed: {
        ...mapGetters(['getScreenWidth']),
        screenWidth() {
        return this.getScreenWidth;
        },
    },
    beforeDestroy(){
        this.chart && this.chart.dispose()
        this.chart1 && this.chart1.dispose()
        window.removeEventListener('scroll', this.handleScroll);
        window.removeEventListener('resize', this.getOffsetTop);
    }
}
</script>

<style scoped>
.contentzw{
    margin:10px auto 0;
    display: flex;
    justify-content: space-between;
}
.contentzwLeft{
    box-sizing: border-box;
    width:184px;
    background:#fff;
    padding:14px 0;
    transition: all 0.2s ease;
}
.fixed {
  position: fixed;
  top: 0;
  z-index: 999;
  /* 宽度需要保持与原来一致，可根据父级宽度自行调整 */
  width: 184px;
}
.searchtopbox{
    padding:0 14px;
}
.contentzwLeft span{
    display: block;
    font-size:12px;
    color:#B3B8C2;
    text-align: center;
    padding:14px 0 14px;
    border-bottom:solid 1px #F5F6F8;
}
.contentzwLeft ul{
    height:calc(100vh - 400px);
    overflow-y:auto;
}
.contentzwLeft ul::-webkit-scrollbar {
    width: 3px;
}
.contentzwLeft ul::-webkit-scrollbar-track {
    background: #f5f5f5;
    border-radius: 3px;
}
.contentzwLeft ul::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}
.contentzwLeft ul li{
    box-sizing: border-box;
    height:42px;
    padding:0 14px;
    cursor: pointer;
    color: rgba(142, 150, 164, 1);
    line-height:42px;
    font-size:14px;
    white-space: nowrap;      /* 不换行 */
    overflow: hidden;         /* 超出隐藏 */
    text-overflow: ellipsis;  /* 超出部分用 … 表示 */
}
.contentzwLeft ul li:hover,.contentzwLeft ul li.hover{
    color: #fff;
    background:rgba(26, 72, 219, 1);
}
.contentzwLeft ul li i.active{
    color:rgba(26, 72, 219, 1);
    font-size:16px;
}
.contentzwLeft ul li:hover i.active,.contentzwLeft ul li.hover i.active{
    color:#fff;
}
.contentzwLeft ul li i{
    display: inline-block;
    margin-right:5px;
}
.contentzwRight{
    box-sizing: border-box;
    width:calc(100% - 195px);
    background:#fff;
    padding:20px;
}
.contentzwLeft >>> .el-select{
    margin-bottom:14px;
}
.subobjquestion{
    display: flex;
    justify-content: space-between;
    margin-bottom:10px;
}
.subobjquestionTitle{
    display: flex;
    align-items: center;
    font-weight: 500;
    font-size: 18px;
    color: #2A303B;
    background:url(../../assets/image/fenxi/title.png) no-repeat left center;
    background-size:12px 8px;
    padding-left:20px;
}
.subobjquestionTitle div{
    margin-left:40px;
}
.subobjquestionTitle b{
    font-size:12px;
    display: inline-block;
    margin-left:20px;
    color:#1A48DB;
    cursor: pointer;
}
.subobjquestion span{
    display: inline-block;
    width: 68px;
    height: 22px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: normal;
    line-height: 22px;
    text-align: center;
    cursor: pointer;
    background: #E8F3FF;
    color:#1A48DB;
}
.lookquestioncard{
    color:#1A48DB;
    cursor: pointer;
}
.lookquestioncard:hover{
    text-decoration: underline;
}
.studentAvgDate{
    display: flex;
    justify-content: space-between;
    padding-bottom:30px;
}
.studentAvgDateLeft,.studentAvgDateRight{
    padding-top:30px;
    width:49%;
}
.studentAvgDateLeftContent{
    width:100%;
    height:224px;
    border: 1px solid rgba(216, 228, 240, 0.5);
}
.answerBox >>> .el-table--enable-row-transition .el-table__body td.el-table__cell{
    text-align: center;
}
.answerBox >>> .el-table td.el-table__cell, .answerBox >>> .el-table th.el-table__cell.is-leaf{
    text-align: center;
}
</style>
